package com.wsoft.excel.handler;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.wsoft.excel.config.ExcelWatermarkConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 用于 Excel 导出 自定义水印
 * @Author z001
 * @Date 2024/11/6 18:11
 */
@Slf4j
public class ExcelWaterMarkHandler implements SheetWriteHandler {

    private final ExcelWatermarkConfig excelWatermarkConfig;


    public ExcelWaterMarkHandler(ExcelWatermarkConfig excelWatermarkConfig) {
        this.excelWatermarkConfig = excelWatermarkConfig;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        if(StrUtil.isNotBlank(excelWatermarkConfig.getContent())){
            try (ByteArrayOutputStream waterMark = createWaterMark()){
                SXSSFSheet sheet = (SXSSFSheet) writeSheetHolder.getSheet();
                putWaterRemarkToExcel(sheet, waterMark.toByteArray());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 创建水印
     * @param content
     * @return
     * @throws IOException
     */
    public  ByteArrayOutputStream createWaterMark() throws IOException {
        // 获取水印相关参数
        Font font = excelWatermarkConfig.getFont();
        //通过width和height 可以控制水印的 疏密程度
        int width = excelWatermarkConfig.getWidth();
        int height = excelWatermarkConfig.getHeight();
        Color color = excelWatermarkConfig.getColor();
        String content = excelWatermarkConfig.getContent();

        // 获取bufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取Graphics2d对象
        Graphics2D g2d = image.createGraphics();
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d.dispose();
        g2d = image.createGraphics();
        //设置字体颜色和透明度
        g2d.setColor(color);
        // 设置字体
        g2d.setStroke(new BasicStroke(1));
        // 设置字体类型 加粗 大小
        g2d.setFont(font);
        //设置倾斜度
        g2d.rotate(-0.5, (double) image.getWidth() / 2, (double) image.getHeight() / 2);
        FontRenderContext context = g2d.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(content, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = -bounds.getY();
        double baseY = y + ascent;
        // 写入水印文字原定高度过小，所以累计写水印，增加高度
        g2d.drawString(content, (int) x, (int) baseY);
        // 设置透明度
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 释放对象
        g2d.dispose();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        return os;
    }

    /**
     * Excel 水印工具函数
     * @param sheet excel sheet
     * @param bytes 水印图片字节数组
     */
    public static void putWaterRemarkToExcel(SXSSFSheet sheet, byte[] bytes) {
        SXSSFWorkbook workbook = sheet.getWorkbook();
        XSSFSheet shReflect = (XSSFSheet) ReflectUtil.getFieldValue(sheet, "_sh");
        int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
        XSSFPictureData xssfPictureData = (XSSFPictureData) workbook.getAllPictures().get(pictureIdx);
        PackagePartName ppn = xssfPictureData.getPackagePart().getPartName();
        PackageRelationship pr = shReflect.getPackagePart().addRelationship(ppn, TargetMode.INTERNAL, XSSFRelation.IMAGES.getRelation(), null);
        shReflect.getCTWorksheet().addNewPicture().setId(pr.getId());
    }

}
